<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑用户' : '新建用户'"
    width="500px"
    :before-close="handleClose"
  >
    <div v-loading="loading">
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="isEdit" />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <!-- <el-form-item label="角色" prop="roles">
          <el-select v-model="userForm.roles" multiple placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="操作员" value="operator" />
            <el-option label="医生" value="doctor" />
            <el-option label="用户" value="user" />
          </el-select>
        </el-form-item> -->
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="active">活跃</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { createUser, updateUser } from '@/api/user.js'

interface User {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  roles: string[]
  status: string
}

interface Props {
  modelValue: boolean
  user?: User
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = ref(false)
const loading = ref(false)
const isEdit = ref(false)

const userFormRef = ref<FormInstance>()
const userForm = ref({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  roles: [] as string[],
  status: 'active',
  password: ''
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ]
}

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    if (props.user) {
      isEdit.value = true
      // 填充表单数据
      userForm.value = {
        username: props.user.username,
        nickname: props.user.nickname,
        email: props.user.email,
        phone: props.user.phone || '',
        roles: [...props.user.roles || []],
        status: props.user.status || 'active',
        password: ''
      }
    } else {
      isEdit.value = false
      // 重置表单
      userForm.value = {
        username: '',
        nickname: '',
        email: '',
        phone: '',
        roles: [],
        status: 'active',
        password: ''
      }
    }
  }
})

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    // 重置表单
    if (userFormRef.value) {
      userFormRef.value.resetFields()
    }
  }
})

const handleClose = () => {
  visible.value = false
}

const saveUser = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      if (isEdit.value && props.user) {
        // 更新用户
        await updateUser(props.user.id, userForm.value)
        ElMessage.success('用户更新成功')
      } else {
        // 创建用户
        await createUser(userForm.value)
        ElMessage.success('用户创建成功')
      }
      
      handleClose()
      emit('refresh')
    } catch (error) {
      ElMessage.error('保存用户失败')
      console.error(error)
    } finally {
      loading.value = false
    }
  })
}
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>